package irv3

import (
	"bytes"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

type DeviceZoneData struct {
	CameraZoneId int       `orm:"Column(cameraZoneId)"`
	StartTime    string    `orm:"Column(startTime)"`
	EndTime      string    `orm:"Column(endTime)"`
	DeviceId     string    `orm:"Column(deviceId)"`
	DeviceZoneId int       `orm:"Column(deviceZoneId)"`
	DateTime     time.Time `orm:"Column(dateTime)"`
	CountIn      int       `orm:"Column(countIn)"`
	CountOut     int       `orm:"Column(countOut)"`
}

func SelectDeviceZoneId() (*[]int, error) {
	o := orm.NewOrm()
	o.Using("irv3")
	data := new([]int)
	sql := "SELECT DISTINCT fk_device_zone_id FROM r_sitezone_devicezone"
	_, err := o.Raw(sql).QueryRows(data)
	return data, err
}
func SelectPhysicalData(date string) (*[]DeviceZoneData, error) {
	o := orm.NewOrm()
	o.Using("irv3")
	data := new([]DeviceZoneData)
	sql := "SELECT 5min as dateTime,site_zone_id as cameraZoneId ,count_in as countIn,count_out as countOut FROM sitezone_5min_all_v1 WHERE date_day = ?"
	_, err := o.Raw(sql, date).QueryRows(data)
	return data, err
}

func SelectDeviceZoneData_new(deviceZoneIds []int, date string) (*[]DeviceZoneData, error) {
	o := orm.NewOrm()
	o.Using("irv3")
	data := new([]DeviceZoneData)
	sql := fmt.Sprintf("SELECT  fk_device_zone_id AS cameraZoneId,  date_time AS dateTime,  count_in as countIn,  count_out as countOut"+
		" FROM  records_inout_partitioned WHERE  fk_device_zone_id in %s and  date = ? ", ReturnInStr(len(deviceZoneIds)))
	_, err := o.Raw(sql, deviceZoneIds, date).QueryRows(data)
	return data, err
}

func SelectDeviceZoneData(deviceZoneIds []int, date string) (*[]DeviceZoneData, error) {
	o := orm.NewOrm()
	o.Using("irv3")
	data := new([]DeviceZoneData)
	sql := fmt.Sprintf("SELECT dcz.Id AS cameraZoneId,	dcz.StartTime AS startTime,dcz.EndTime AS endTime,ff.* FROM "+
		"( SELECT device._name AS deviceId,device_zone.id AS deviceZoneId,date_time AS dateTime, "+
		"count_in AS countIn,count_out AS countOut FROM device INNER JOIN device_zone ON device.id = "+
		"device_zone.fk_device_id INNER JOIN (SELECT * FROM records_inout_partitioned WHERE fk_device_zone_id in %s AND date = ? )"+
		" f ON device_zone.id = f.fk_device_zone_id) ff INNER JOIN device_cameraZoneId dcz ON ff.deviceId=dcz.DeviceId", ReturnInStr(len(deviceZoneIds)))
	_, err := o.Raw(sql, deviceZoneIds, date).QueryRows(data)
	return data, err
}

func ReturnInStr(len int) string {
	var inStr bytes.Buffer
	inStr.WriteString("(")
	for i := 0; i < len-1; i++ {
		inStr.WriteString("?,")
	}
	inStr.WriteString("? )")
	return inStr.String()
}
